package ThreadDemo;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch 限定线程都结束才能结束，不然就一直等待
 */
public class TreadDemo18 {
    public static void main(String[] args) throws InterruptedException {
        //限定需要完成线程的数量
        CountDownLatch latch=new CountDownLatch(4);
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                System.out.println("准备");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("起跑");
                try {
                    Thread.sleep((long) (Math.random()*10000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                latch.countDown();//给里面的计数器减一
                System.out.println("到达终点");

            }
        };
        for (int i = 0; i < 4; i++) {
            Thread thread=new Thread(runnable);
            thread.start();

        }
        //四个线程都走完，里面的计数器为0，结束
        latch.await();
        System.out.println("比赛结束");


    }
}
